//
//  BYCountDownButton.m
//  ZhaoQiPei
//
//  Created by 找汽配ios开发 on 15/12/28.
//  Copyright © 2015年 祥运. All rights reserved.
//

#import "XYCountDownButtonManager.h"

@interface XYCountDownButtonManager ()

@property (nonatomic, assign) NSInteger countingDownNumber;
@property (nonatomic, assign) NSInteger status; // 状态，1：未启用；2：正在进行；3：已结束
@property (nonatomic, strong) NSTimer * timer;

@end

@implementation XYCountDownButtonManager

DEF_SINGLETON(XYCountDownButtonManager)

- (instancetype)init {
    self = [super init];
    if (self) {
        self.status = 1;
    }
    return self;
}

#pragma mark - Setup

- (void)reloadButton {
    if (self.status == 1) {
        if (self.initializationBlock) {
            self.initializationBlock(self.button);
        }
    }
    else if (self.status == 2) {
        if (self.preparationBlock) {
            self.preparationBlock(self.button);
        }
        if (self.countingBlock) {
            self.countingBlock(self.button, self.countingDownNumber);
        }
    }
    else if (self.status == 3) {
        if (self.completionBlock) {
            self.completionBlock(self.button);
        }
    }
}

#pragma mark - Controller

- (void)start {
    [self startCountDown];
}

- (void)preparation {
    if (self.preparationBlock) {
        self.preparationBlock(self.button);
    }
}

- (void)completion {
    if (self.status == 1) {
        if (self.initializationBlock) {
            self.initializationBlock(self.button);
        }
    }
    else if (self.status == 3) {
        if (self.completionBlock) {
            self.completionBlock(self.button);
        }
    }
}

#pragma mark - Action

- (void)startCountDown {
    [self stopCountDown];

    self.countingDownNumber = self.countDownNumber;
    self.status = 2;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fire];
}

- (void)stopCountDown {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)countDown {
    if (self.countingDownNumber >= 0) {
        if (self.countingBlock) {
            self.countingBlock(self.button, self.countingDownNumber);
        }
        --self.countingDownNumber;
    }
    else {
        self.status = 3;
        [self stopCountDown];
        if (self.completionBlock) {
            self.completionBlock(self.button);
        }
    }
}

#pragma mark - Button Action

- (void)buttonTouchUpInside {
    if (self.clickedBlock) {
        self.clickedBlock(self.button);
    }
}

#pragma mark - Setter

- (void)setButton:(UIButton *)button {
    _button = button;
    [button addTarget:self action:@selector(buttonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self reloadButton];
}

@end
